package com.chensi.admin.web.controller;

import com.chensi.admin.web.domain.SysUserToken;
import com.chensi.admin.web.domain.WebUser;
import com.chensi.admin.web.exception.BaseException;
import com.chensi.admin.web.service.SysLoginService;
import com.chensi.admin.web.service.WebUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: si.chen
 * @Date: 2019/6/20 13:57
 */
public abstract class BaseController {

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private WebUserService webUserService;

    @Autowired
    private HttpServletRequest request;

    WebUser getUser() throws BaseException {
        //return (WebUser) SecurityUtils.getSubject().getPrincipal();
        String token = getRequestToken(request);
        SysUserToken sysUserToken = sysLoginService.getUserToken(token);
        return webUserService.get(sysUserToken.getUserId());

    }

    String getUserId() throws BaseException {
        return getUser().getId();
    }

    private String getRequestToken(HttpServletRequest httpRequest) {
        String token = httpRequest.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = httpRequest.getParameter("token");
        }
        return token;
    }

}
